package com.unsafe5_lock6;
class TicketSaleRunnable implements Runnable{
    private int ticket = 100;
    @Override
    public void run() {//直接锁这里，肯定不行，会导致，只有一个窗口卖票
        while (ticket>0){
            saleOneTicket();
        }
    }
    public  synchronized void saleOneTicket(){
//        锁的对象是this，这里就是TicketSaleRunnable对象，因为上面
//        3个线程使用同一个TicketSaleRunnable对象，所以可以
        if (ticket>0){//不加条件，相当于判断条件没有进入锁管控，
            // 线程安全问题就没有解决
            System.out.println(Thread.currentThread().getName() + "卖出一张票，票号：" + ticket);
            ticket--;
        }
    }
}
// 非静态方法加锁
public class SaleTicketDemo4 {
    public static void main(String[] args) {
        TicketSaleRunnable tr = new TicketSaleRunnable();
        Thread t1 = new Thread(tr,"窗口1");
        Thread t2 = new Thread(tr,"窗口2");
        Thread t3 = new Thread(tr,"窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}
